package com.runen.infinitemovement.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.runen.infinitemovement.R;
import com.runen.infinitemovement.model.enums.ActivityCompat;
import com.runen.infinitemovement.picker.DateUtils;
import com.runen.infinitemovement.service.LocationService;
import com.runen.infinitemovement.tool.ActivityUtils;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.widget.SildingFinishLayout;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Create by LiaoDuanHong
 * Create on
 */
public class LockScreenActivity extends AppCompatActivity {

    private TextView tvUserTime;
    private TextView tvSpeed;
    private TextView tvDistance;
    private TextView tv_time;
    private TextView tv_date;
    private SildingFinishLayout rl_content;
//    private LockScreenBroadcastReceiver locationReceiver;

    public long usedTime;
    private boolean isPause = false;
    public double mDistance = 0;
    private MyHandler myHandler;
    private Timer timer;
    private TimerTask timerTask;

    public static final int MSG_REPLY = 101;
    /**
     * Messenger for communicating with the service.
     */
    Messenger mService = null;

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_REPLY:
                    Bundle bundleReserve = msg.getData();
                    mDistance = bundleReserve.getDouble("distance");
                    isPause = bundleReserve.getBoolean("isPause");
                    setDistance(mDistance);
                    Log.e("123456", "handler-MSG_REPLY    mDistance:" + mDistance + "  isPause:" + isPause);

            }
            return false;
        }
    });

    public void sayHello() {
        Log.e("123456", "sayHello()");
        Message msg = Message.obtain();
        msg.what = LocationService.MSG_LOCK_SCREEN_FROM_CLIENT;
        msg.replyTo = new Messenger(handler);
        try {
            mService.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    private static class MyHandler extends Handler {
        WeakReference<Activity> reference;

        public MyHandler(Activity activity) {
            reference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            if (null != reference) {
                LockScreenActivity activity = (LockScreenActivity) reference.get();
                if (null != activity) {
                    if (msg.what == 1) {
                        activity.usedTime++;
                        activity.tvUserTime.setText(activity.timeConversion((int) activity.usedTime));
                    }
                }
            }
        }
    }

    private boolean isTranslucentOrFloating() {
        boolean isTranslucentOrFloating = false;
        try {
            int[] styleableRes = (int[]) Class.forName("com.android.internal.R$styleable").getField("Window").get(null);
            final TypedArray ta = obtainStyledAttributes(styleableRes);
            Method m = ActivityInfo.class.getMethod("isTranslucentOrFloating", TypedArray.class);
            m.setAccessible(true);
            isTranslucentOrFloating = (boolean) m.invoke(null, ta);
            m.setAccessible(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isTranslucentOrFloating;
    }

    private boolean fixOrientation() {
        try {
            Field field = Activity.class.getDeclaredField("mActivityInfo");
            field.setAccessible(true);
            ActivityInfo o = (ActivityInfo) field.get(this);
            o.screenOrientation = -1;
            field.setAccessible(false);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    //在设置方向的时候如果透明，直接不执行
    @Override
    public void setRequestedOrientation(int requestedOrientation) {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
            return;
        }
        super.setRequestedOrientation(requestedOrientation);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        //8.0处理系统bug（8.0屏幕透明不能指定方向）
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
            fixOrientation();
        }
        super.onCreate(savedInstanceState);
        this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                        View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |// hide nav
                        View.SYSTEM_UI_FLAG_IMMERSIVE
        );
        setContentView(R.layout.activity_lock_screen);
        ActivityUtils.getInstance().addActivity(this);
        tvUserTime = findViewById(R.id.tv_user_time);
        tvSpeed = findViewById(R.id.tv_speed);
        tvDistance = findViewById(R.id.tv_distance);
        tv_time = findViewById(R.id.tv_time);
        tv_date = findViewById(R.id.tv_date);
        rl_content = findViewById(R.id.rl_content);
        rl_content.setOnSildingFinishListener(new SildingFinishLayout.OnSildingFinishListener() {
            @Override
            public void onSildingFinish() {
                finish();
            }
        });
        rl_content.setTouchView(getWindow().getDecorView());

        myHandler = new MyHandler(this);

        usedTime = getIntent().getLongExtra(ActivityCompat.USER_TIME, 0) / 1000;
        tvUserTime.setText(timeConversion((int) usedTime));

        Intent intent = new Intent(this, LocationService.class);
        bindService(intent, mConnection, 0);//不启动locationservice

//        locationReceiver = new LockScreenBroadcastReceiver();
//        IntentFilter filter = new IntentFilter();
//        filter.addAction("com.runen.lockScreen");
//        registerReceiver(locationReceiver, filter);

        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                if (mService != null)
                    sayHello();
                if (!isPause)
                    myHandler.sendEmptyMessage(1);
            }
        };
        timer.schedule(timerTask, 0, 1000);
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
//            Log.e("123456", "ServiceConnection-onServiceConnected");
            mService = new Messenger(service);
        }

        public void onServiceDisconnected(ComponentName className) {
//            Log.e("123456", "ServiceConnection-onServiceDisconnected");
            mService = null;
        }
    };


    private class LockScreenBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
//            if (count == 0)
//            usedTime = bundle.getLong("userTime") / 1000;
//            count++;
            mDistance = bundle.getDouble("distance");
            isPause = bundle.getBoolean("isPause");
            Log.e("123456", "onReceive: mDistance" + mDistance);
            Log.e("123456", "onReceive: isPause" + isPause);
        }
    }

    public void setDistance(double mDistance) {
        tvDistance.setText(String.valueOf(CommonUtil.Double2position(mDistance / 1000)));
        tv_time.setText(DateUtils.formatDate(new Date(), "HH:mm"));
        Date date = new Date();
        tv_date.setText(getWeek(DateUtils.formatDate(date, "yyyy-MM-dd"))
                + DateUtils.formatDate(date, "MM月dd日"));

        int speed_allocationInt = 0;
        int speed_allocationMode = 0;
        double mm = (double) usedTime / 60;
        double averageSpeed = 0;
        if (mDistance > 0 && usedTime > 0) {
            double km = mDistance / 1000;
            speed_allocationInt = (int) (mm / km);
            double ss = mm % km;
            speed_allocationMode = (int) ss;
            double t = (double) (usedTime / 3600);
            if (km > 0 && t > 0) {
                averageSpeed = km / t;
            }

            tvSpeed.setText(speed_allocationInt + "'" + speed_allocationMode + "''");
        }
    }

    public static String getWeek(String time) {
        String Week = "";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        try {
            c.setTime(format.parse(time));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            Week += "周天";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
            Week += "周一";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY) {
            Week += "周二";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY) {
            Week += "周三";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY) {
            Week += "周四";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
            Week += "周五";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
            Week += "周六";
        }
        return Week;
    }

    public String timeConversion(int time) {
        int hour = 0;
        int minutes = 0;
        int sencond = 0;
        int temp = time % 3600;
        if (time > 3600) {
            hour = time / 3600;
            if (temp != 0) {
                if (temp > 60) {
                    minutes = temp / 60;
                    if (temp % 60 != 0) {
                        sencond = temp % 60;
                    }
                } else {
                    sencond = temp;
                }
            }
        } else {
            minutes = time / 60;
            if (time % 60 != 0) {
                sencond = time % 60;
            }
        }
        return (hour < 10 ? ("0" + hour) : hour) + ":" + (minutes < 10 ? ("0" + minutes) : minutes) + ":" + (sencond < 10 ? ("0" + sencond) : sencond);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        unregisterReceiver(locationReceiver);
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
        myHandler.removeCallbacksAndMessages(null);
//        if (isBind) unbindService(mConnection);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // Unbind from the service
//        unbindService(mConnection);
    }
}
